<?php

namespace app\services\activity\coupon;

use app\dao\activity\coupon\StoreCouponDao;
use app\model\activity\coupon\StoreCoupon;
use app\model\product\sku\StoreProductStockRelation;
use app\services\BaseServices;
use crmeb\exceptions\AdminException;

class StoreCouponServices extends BaseServices
{
    public function __construct(StoreCouponDao $dao)
    {
        $this->dao = $dao;
    }


    public function getList($where)
    {
        $title = $where['title'] ?? '';
        $status = (isset($where['status']) && $where['status'] != '') ? $where['status'] : -1;
        $time_status = (isset($where['time_status']) && $where['time_status'] != '') ? $where['time_status'] : -1;

        $storeCoupons = StoreCoupon::with(['couponProduct.product'])->where('create_type', 0)->where('is_del', 0)->when($title, function ($query) use ($title) {
            $query->where('title', 'like', '%' . $title . '%'); // 使用 like 来进行模糊匹配
        })->when($status != -1 , function ($query) use ($status) {
            $query->where('status', $status);
        })->when($time_status != -1, function ($query) use ($time_status) {
            if ($time_status == 0) {
                $query->where('start_time', '>', time());
            } else if ($time_status == 1) {
                $query->where('start_time', '<=', time())->where('end_time', '>', time());
            } else if ($time_status == 2) {
                $query->where('end_time', '<=', time());
            }
        })->paginate($where['limit'] ?? 15);

//        $list = $storeCoupons->items();

        $list = [];
        foreach ($storeCoupons->items() as $item) {
            $time_status = 0;
            if (time() >= $item['start_time'] && time() < $item['end_time']) {
                $time_status = 1;
            } else if (time() >= $item['end_time']){
               $time_status = 2;
            }

            $item['time_status'] = $time_status;
            $list[] = $item;
        }

        $count = $storeCoupons->count();
        return compact('list', 'count');

    }

    /**
     * @param int $id
     * @param array $data
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function save(int $id, array $data)
    {
        $title = $data['title'] ?? '';
        $total_count = $data['total_count'] ?? 0;
        $is_use_all_product = $data['is_use_all_product'] ?? -1;
        $has_use_limit = $data['has_use_limit'] ?? -1;
        $use_min_price = $data['use_min_price'] ?? 0;
        $price = $data['price'] ?? 0;
        $start_time = $data['start_time'] ?? -1;
        $end_time = $data['end_time'] ?? -1;
        $use_day = $data['use_day'] ?? -1;
        $available_type = $data['available_type'] ?? -1;
        $has_get_limit = $data['has_get_limit'] ?? -1;
        $get_max_count = $data['get_max_count'] ?? 0;
        $status = $data['status'] ?? -1;
        $products = $data['products'] ?? [];
        $create_type = $data['create_type'] ?? 0;

        if ($has_use_limit == 0) {
            $use_min_price = 0;
        }
        if ($available_type == 1) {
            $use_day = 0;
        }
        if ($available_type == 2) {
            $start_time = $end_time = 0;
        }
        if ($has_get_limit == 0) {
            $get_max_count = 0;
        }

        if ($is_use_all_product == 1) {
            $products = [];
        }

        if ($title == '') throw new AdminException(400372);
        if ($total_count == 0) throw new AdminException(30035);
        if (!in_array($is_use_all_product, [1, 0])) throw new AdminException(30036);
        if (!in_array($has_use_limit, [1, 0])) throw new AdminException(30037);
        if ($has_use_limit == 1 && $use_min_price == 0) throw new AdminException(400375);
        if ($price == 0) throw new AdminException(400374);
        if (!in_array($available_type, [1, 2])) throw new AdminException(30038);
        if ($available_type == 1 && ($start_time == -1 || $end_time == -1)) throw new AdminException(30039);
        if ($available_type == 1 && ($start_time >= $end_time)) throw new AdminException(30040);
        if ($available_type == 2 && !$use_day) throw new AdminException(30041);
        if (!in_array($has_get_limit, [1, 2])) throw new AdminException(30042);
        if ($has_get_limit = 1 && !$get_max_count) throw new AdminException(30043);
        if (!in_array($available_type, [1, 2])) throw new AdminException(400376);
        if ($is_use_all_product == 0 && empty($products)) throw new AdminException(30044);

        $data  = [
                'title' => $title,
                'total_count' => $total_count,
                'is_use_all_product' => $is_use_all_product,
                'has_use_limit' => $has_use_limit,
                'use_min_price' => $use_min_price,
                'price' => $price,
                'start_time' => $start_time,
                'end_time' => $end_time,
                'use_day' => $use_day,
                'available_type' => $available_type,
                'has_get_limit' => $has_get_limit,
                'get_max_count' => $get_max_count,
                'status' => $status,
                'create_type' => $create_type,
            ];

        if ($id) {
            $coupon = $this->dao->get($id);
            if (!$coupon) throw new AdminException(400515);
            $this->dao->update($id, $data);
        } else {
            $data['add_time'] = time();
            $data['status'] = 1;

            $res = $this->dao->save($data);
            $id = $res->id;
        }

        // 维护优惠劵关联关系表
        if ($id && $is_use_all_product == 0 && !empty($products)) {
            $storeCouponProductServices = app()->make(StoreCouponProductServices::class);
            $storeCouponProductServices->syncRelation($id, $products);
        }
        return $id;
    }

    public function detail($id)
    {
        $coupon = StoreCoupon::with(['couponProduct.product', 'couponProduct.attrInfo'])->where('id', $id)->find();
        if (!$coupon) return [];

        $products = $coupon->couponProduct()->select();


        $product_arr = [];
        foreach ($products as $item) {
            $relation = StoreProductStockRelation::where('product_attr_value_unique', $item->product_attr_value_unique)->find();

            $product_arr[] = [
                'product_id' => $item->product_id,
                'image' =>  $item->attrInfo ? $item->attrInfo->image : '',
                'store_name' => $item->product ? $item->product->store_name : '',
                'suk'   =>  $item->attrInfo ? $item->attrInfo->suk : '',
                'bar_code'  =>  $item->attrInfo ? $item->attrInfo->bar_code : '',
                'price' =>  $item->attrInfo ? $item->attrInfo->price : '',
                'stock' =>  $relation ? $relation->total_stock : 0,
                'product_attr_value_unique' => $item->product_attr_value_unique,
            ];
        }

        $coupon->products = $product_arr;
        unset($coupon->couponProduct);

        return $coupon->toArray();

    }


    public function setShow($ids, $status)
    {
        $this->dao->batchUpdate($ids, ['status' => $status]);
        return true;
    }

}